package stardust.product.j2d.chart;


import java.awt.Color;
import java.awt.Graphics;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import stardust.product.j2d.GraphicsObject;


public class LineChart extends GraphicsObject
{
	
	public static final int PLAN_OFFSET_WIDTH = 10;
	public static final int LINE_OFFSET_WIDTH = 5;
	
	public static class LineData
	{
		
		public int length;
		
		public List<Integer> data = new ArrayList<Integer>();
		
		public Color color = Color.GREEN;
		
		public void add(Integer d)
		{
			while (this.data.size() > this.length)
			{
				this.data.remove(0);
			}

			this.data.add(d);
		}
		
	}
	
	private List<LineData> data = new ArrayList<LineData>();
	
	public LineChart(int x, int y, int width, int height)
	{
		super.setX(x);
		super.setY(y);
		super.setWidth(width);
		super.setHeight(height);
	}
	
	private int offset = 0;

	public void paint(Graphics g, int x, int y)
	{
		LineData ld;
		
		g.setColor(new Color(0, 128, 64));
		
		if (offset++ > PLAN_OFFSET_WIDTH / LINE_OFFSET_WIDTH)
		{
			offset = 0;
		}
		
		for (int i = x; i < x + this.getWidth() + offset; i += LineChart.PLAN_OFFSET_WIDTH)
		{
			g.drawLine(i + PLAN_OFFSET_WIDTH - offset * LINE_OFFSET_WIDTH, y, i + PLAN_OFFSET_WIDTH -  offset * LINE_OFFSET_WIDTH, y + this.getHeight());
		}
		
		for (int i = y; i < y + this.getHeight(); i += LineChart.PLAN_OFFSET_WIDTH)
		{
			g.drawLine(x, i, x + this.getWidth(), i);
		}
		
		int maxValue = getMaxValue();
		
		for (int i = 0; i < this.data.size(); i++)
		{
			ld = this.data.get(i);
			g.setColor(ld.color);
			
			for (int j = 0; j < ld.data.size(); j ++)
			{
				int bx = j == 0 ? 0 : x + ((j - 1) * LineChart.LINE_OFFSET_WIDTH);
				int by = j == 0 ? y + this.getHeight() : y + this.getHeight() - (int) ((ld.data.get(j - 1) / (double) maxValue) * this.getHeight());
				by = by > maxValue ? maxValue : by++;
				
				int nx = x + j * LineChart.LINE_OFFSET_WIDTH;
				int ny = y + this.getHeight() - (int) ((ld.data.get(j) / (double) maxValue) * this.getHeight());
				ny = ny > maxValue ? maxValue : ny++;

				g.drawLine(bx, by, nx, ny);
			}
		}
	}
	
	public int getMaxValue()
	{
		LineData ld;
		int maxValue = 0;
		
		for (int i = 0; i < this.data.size(); i++)
		{
			ld = this.data.get(i);
			
			for (int j = 0; j < ld.data.size(); j ++)
			{
				maxValue = Math.max(maxValue, ld.data.get(j));
			}
		}
		
		return maxValue;
	}
	
	public int getMaxLength()
	{
		return this.getWidth() / LineChart.LINE_OFFSET_WIDTH;
	}

	public List<LineData> getData()
	{
		return data;
	}

	public void setData(List<LineData> data)
	{
		this.data = data;
	}
	
}
